// Library for local database functionality

//bootstrap database
var dbname = 'TCApp';
var db = Ti.Database.open(dbname);
db.execute('CREATE TABLE IF NOT EXISTS favourites(id INTEGER PRIMARY KEY, packageId TEXT);');
db.close();

exports.list = function() {
	var favouriteList = [];
	var db - Ti.Database.open(dbname);
	var result = db.execute('SELECT * from favourites');

	while (result.isValidRow()) {
		favouriteList.push(result.fieldByName('packageId'));
		result.next();
	}

	result.close();
	db.close();

	return favouriteList;
}

exports.add = function(packageId) { 
	if (!exists(packageId)) {
		var db = Ti.Database.open(dbname);
		db.execute('INSERT INTO favourites (packageId) VALUES (?)', packageId);
		db.close();
	}
}

exports.remove = function(packageId) {
	var db = Ti.Database.open(dbname);
	db.execute('DELETE FROM favourites WHERE packageId = ?', packageId);
	db.close();
}

exports.exists = function(packageId) {
	var db = Ti.Database.open(dbname);
	var result = db.execute('SELECT * from favourites WHERE packageId = ?', packageId);
	db.close();
	var retval = (result.rowCount > 0) ? true : false;
	result.close();
	return retval;
}

exports.syncWithArray = function(idArray) {
	var db = Ti.Database.open(dbname);
	db.execute('DELETE FROM favourites');
	
	// iterate through the array and insert the packageIds into the database
	for (var i=0; i<idArray.length; i++) {
		db.execute('INSERT INTO favourites (packageId) VALUES (?)', idArray[i]);
	}
	
	db.close();
}
